package ch.pizzapp.kurier;

import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.rest.RestService;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import ch.pizzapp.kurier.client.InfoClient;
import ch.pizzapp.kurier.data.ResponceData;
import ch.pizzapp.kurier.data.UserResonce;
import ch.pizzapp.kurier.dto.InfoDto;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.activity_login)
public class LoginFromDrawerActivity extends Activity {

	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	// private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// UI references.
	@ViewById(R.id.email)
	EditText mEmailView;

	@ViewById(R.id.password)
	EditText mPasswordView;

	@ViewById(R.id.relativeLayout1)
	View mLoginFormView;

	@ViewById(R.id.login_status)
	View mLoginStatusView;

	@ViewById(R.id.login_status_message)
	TextView mLoginStatusMessageView;

	@Extra("ResponceData")
	ResponceData responceData;

	@ViewById(R.id.linearLayout1)
	View linearLayout1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// System.out.println("login");

		setContentView(R.layout.activity_login);

		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		//getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Click({ R.id.sign_in_button, R.id.textViewPassword })
	void onClick(View view) {
		switch (view.getId()) {
		case R.id.sign_in_button:

			attemptLogin();
			break;

		case R.id.textViewPassword:
			Intent intent = new Intent(LoginFromDrawerActivity.this,
					ForgotPasswordActivity_.class);

			startActivity(intent);
			overridePendingTransition(R.anim.open_next, R.anim.close_main);
			break;

		default:
			break;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			// showProgress(true);
			showProgress(true);
			hide_keyboard(LoginFromDrawerActivity.this);
			doLogin();

		}
	}

	@Bean
	InfoDto infoDto;
	@RestService
	InfoClient InfoClient;

	@Background
	void doLogin() {

		infoDto.setPass(mPassword);
		infoDto.seteMail(mEmail);
		infoDto.setType("1");

		new ReachabilityTest(LoginFromDrawerActivity.this,
				new ReachabilityTest.Callback() {

					@Override
					public void onReachabilityTestPassed() {

						try {
							setLogin(InfoClient.doLogin(infoDto
									.getMultiValuedMap()));
						} catch (Exception e) {

							System.err.println(e);
						}
					}

					@Override
					public void onReachabilityTestFailed() {

						showMessge("Not connected ");
					}
				});
	}

	@UiThread
	void setLogin(final UserResonce userResonce) {
		showProgress(false);
		if (userResonce.getResponse().getMessage() == null) {
			Intent resultIntent = new Intent(LoginFromDrawerActivity.this,
					PlacesActivity_.class);
			resultIntent.putExtra("UserResonce", userResonce);
			resultIntent.putExtra("ResponceData", responceData);
			setResult(Activity.RESULT_OK, resultIntent);
			finish();
		} else {
			showMessge(userResonce.getResponse().getMessage());
		}

	}

	@UiThread
	void showMessge(final String msg) {
		Toast.makeText(LoginFromDrawerActivity.this, msg, Toast.LENGTH_LONG)
				.show();
	}

	@UiThread
	void showProgress(final boolean show) {
		mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
		linearLayout1.setVisibility(show ? View.GONE : View.VISIBLE);
	}

	public void hide_keyboard(Activity activity) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		// Find the currently focused view, so we can grab the correct window
		// token from it.
		View view = activity.getCurrentFocus();
		// If no view currently has focus, create a new one, just so we can grab
		// a window token from it
		if (view == null) {
			view = new View(activity);
		}
		inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
	}
}
